package com.sino.gateway.component;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.jwt.JwtException;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;

import cn.hutool.crypto.SecureUtil;
import reactor.core.publisher.Mono;

public class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
	private static final Logger log = LogManager.getLogger();

	public Mono<JWTClaimsSet> convert(JWT jwt) {
		log.info("jwt >>>>> {}", ReflectionToStringBuilder.toString(jwt));

		JWSObject jwsObject = (JWSObject) jwt;
		JWTClaimsSet jwtClaimsSet = null;
		try {
			// 创建HMAC验证器
			JWSVerifier jwsVerifier = new MACVerifier(SecureUtil.md5("test_key"));
			if (!jwsObject.verify(jwsVerifier)) {
				log.info("===============   token签名不合法！====================");
				throw new JwtException("token签名不合法！");
			}
			jwtClaimsSet = jwt.getJWTClaimsSet();
		} catch (JOSEException | ParseException e) {
			e.printStackTrace();
		}

		long exp = (Long) jwsObject.getPayload().toJSONObject().getOrDefault("exp", 0);
		if (exp < System.currentTimeMillis()/1000) {
			log.info("===============   token已过期！ ====================");
			throw new JwtException("token已过期！");
		}

		return Mono.just(jwtClaimsSet);
	}
}